package com.chance.cc.crawler.development.command.node;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.core.CrawlerJob;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequest;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

/**
 * created by CC on 2020/11/26
 * mail 279020185@qq.com
 */
@Slf4j
public class CrawlerNodeCommand extends com.chance.cc.crawler.development.command.HttpCommand {

    public CrawlerNodeCommand(String host, int port){
        super(host,port);
    }

    public HttpPage killCrawler(CrawlerJob crawlerJob){
        String url = commandUrl("killCrawler");

        return sentRequest(url,crawlerJob);
    }

    public HttpPage nodeStatus(){
        String url = commandUrl("nodeStatus");

        HttpRequest request = new HttpRequest();
        request.setUrl(url);
        request.setMethod(HttpConstant.Method.GET);

        HttpPage httpPage = doCommand(request);
        log.info("crawler node status result : {}",httpPage.getRawText());
        return httpPage;
    }

    public HttpPage registerCrawlerJob(CrawlerJob crawlerJob){
        String url = commandUrl("registerCrawlerJob");
        //compose crawler scheduler job
        //generate request

        return sentRequest(url,crawlerJob);
    }

    public HttpPage killCrawlerController(){
        String url = commandUrl("killCrawlerController");

        return sentRequest(url,null);
    }

    private HttpPage sentRequest(String url,CrawlerJob crawlerJob){
        HttpRequest request = new HttpRequest();
        request.setUrl(url);
        request.setMethod(HttpConstant.Method.POST);
        if (crawlerJob != null){
            request.setRequestBody(HttpRequestBody.json(JSON.toJSONString(crawlerJob),"utf-8"));
        }
        HttpPage httpPage = doCommand(request);
        log.info("response result :");
        log.info(httpPage.getRawText());
        return httpPage;
    }


    @Override
    public String initUrlPrefix(String host,int port) {
        return StringUtils.join("http://",host,":",port,"/crawler/node/api/v1");
    }
}
